<template>
  <!-- 企业管理 -->
  <div class="building-container">
    <!-- 搜索处 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" placeholder="请输入内容" class="search-main" @keyup.enter="doSearch" />
      <el-button type="primary" class="search-btn" @click="doSearch">查询</el-button>
    </div>
    <!-- 表格上面的按钮 -->
    <!-- <auth-button btn-string="park:enterprise:add_edit">
      <el-button size="mini" type="warning" @click="confirmDel(scope.row.id)">添加企业</el-button>

    </auth-button> -->
    <div class="table-container">
      <el-button type="primary" class="search-btn" @click="$router.push('/enterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table-container">
      <el-table :data="tableData" style="width: 100%" @expand-change="handleExpandChange">
        <el-table-column type="expand">

          <template #default="props">
            <el-table :data="props.row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间">
                <template #default="scope">
                  <span>{{ scope.row.startTime }}</span>
                  <span>至</span>
                  <span>{{ scope.row.endTime }}</span>
                </template>
              </el-table-column>
              <el-table-column label="合同状态" prop="status" :formatter="formatStatus">
                <template #default="scope">
                  <el-tag :type="formatInfoType(scope.row.status)">{{ formatStatus(scope.row) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="mini" type="text" @click="continueRent(scope.row.id)">续租</el-button>
                  <!-- 合同id -->

                  <el-button size="mini" type="text" :disabled="scope.row.status === 3" @click="outRent(scope.row.id)">退租</el-button>

                  <el-button size="mini" type="text" :disabled="scope.row.status !== 3">删除</el-button>

                </template>

              </el-table-column>

            </el-table>

          </template>

        </el-table-column>

        <el-table-column type="index" label="序号" width="160" :index="getIndex" />
        <el-table-column prop="name" label="企业名称" width="200" />
        <el-table-column prop="contact" label="联系人" width="180" />
        <el-table-column prop="contactNumber" label="联系电话" width="180" />
        <el-table-column prop="demoFlag" label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="mini" round @click="addRent(scope.row.id)">添加合同</el-button>
            <el-button size="mini" round @click="handleLook(scope.row.id)">查看</el-button>
            <el-button type="text" size="mini" @click="handleEdit( scope.row.id)">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :current-page="params.page"
        :page-size="params.pageSize"
        @current-change="getPageValue"
      />
    </div>
    <!-- 添加合同 -->
    <el-dialog
      :title="rentForm.type===0?'添加合同':'续租合同'"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>
        <el-form ref="ruleRentForm" :model="rentForm" :rules="rentrules">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择楼宇">
              <el-option
                v-for="item in bulidingList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <div class="block">

              <el-date-picker
                v-model="rentForm.rentTime"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </div>

          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              class="upload-demo"
              action="#"
              :http-request="uploadRequest"
              :before-upload="beforeUpload"
            >
              <br>
              <el-button size="small" type="primary" plain class="upload-btn"><i class="el-icon-upload2" />点击上传</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.png .jpg .jpeg，文件大小不得超过5M</div>
            </el-upload>

          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddrent">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getEnterpriseList, deleteEnterprise, uploadAPI, getBuildingList, addRentContract, getRentContractList, outRentAPI } from '@/api/enperprise'

export default {
  name: 'Building',
  data() {
    return {
      rentid: 0, // 企业id
      rentList: [], // 合同租赁列表
      // exterpriseList: [], // 合同列表
      // RentContractList: [], // 合同列表
      rentForm: {
        rentTime: [],
        contractId: '', // 租赁合同id
        buildingId: '', // 楼宇id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业id
        type: 0 // 合同类型

      },
      rentrules: {

        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]

      },
      bulidingList: [], // 楼宇列表

      dialogVisible: false,

      params: {
        page: 1,
        pageSize: 5,
        name: ''
      },
      total: 0,
      tableData: []
    }
  },
  watch: {
    rentList: {
      deep: true,
      handler(newVal, oldVal) {
        this.rentList = newVal
        this.getEnterpriseList()
      }
    }
  },
  created() {
    this.getEnterpriseList()
  },
  methods: {

    async getEnterpriseList() {
      const res = await getEnterpriseList({ page: this.params.page, pageSize: this.params.pageSize, name: this.params.name })
      // console.log(res)
      this.tableData = res.data.rows.map((item) => {
        return {
          ...item,
          rentList: this.rentList// 每一行补充存放合同的列表
        }
      })
      // console.log(this.tableData)

      this.total = res.data.total
    },
    // 获取分页数据
    getPageValue(val) {
      this.params.page = val
      this.getEnterpriseList()
    },
    // 序号
    getIndex(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1
    },
    // 搜索
    doSearch() {
      this.getEnterpriseList()
      // 搜索过后让页码回到第一页
      this.params.page = 1
    },
    // 编辑企业
    handleEdit(id) {
      this.$router.push({
        path: '/enterpriseEdit',
        query: {
          id
        }
      })
    },
    async handleDelete(id) {
      await deleteEnterprise(id)
      this.getEnterpriseList()
    },
    // 添加合同弹窗
    async addRent(id) {
      this.rentForm.enterpriseId = id
      this.rentForm.type = 0
      this.dialogVisible = true
      // 获取楼宇
      const res = await getBuildingList()
      // console.log(res)
      this.bulidingList = res.data.rows
    },
    async uploadRequest(data) {
      // console.log(data)
      const file = data.file
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'contract')
      const res = await uploadAPI(formData)
      // console.log(res)

      this.rentForm.contractUrl = res.data.url
      this.rentForm.contractId = res.data.id

      // 手动触发上传文件的表单校验
      this.$refs.ruleForm.validateField('contractId')
    },

    // 上传文件之前的钩子
    beforeUpload(file) {
      const allowImgType = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        this.$message.error('上传合同图片只能是 PNG/JPG/JPEG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传合同图片大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    // 添加合同
    handleAddrent() {
      // console.log(this.rentForm.rentTime[0])

      this.$refs.ruleRentForm.validate(async(result) => {
        if (result) {
          if (this.rentForm.type === 0) {
            const { contractId, buildingId, contractUrl, enterpriseId } = this.rentForm
            await addRentContract({ contractId, buildingId, contractUrl, enterpriseId, type: 0, startTime: this.rentForm.rentTime[0], endTime: this.rentForm.rentTime[1] })
          }
          if (this.rentForm.type === 1) {
            const { contractId, buildingId, contractUrl, enterpriseId } = this.rentForm
            await addRentContract({ contractId, buildingId, contractUrl, enterpriseId, type: 1, startTime: this.rentForm.rentTime[0], endTime: this.rentForm.rentTime[1] })
          }

          this.getEnterpriseList()
        }
      })

      this.dialogVisible = false
    },
    // 关闭合同弹窗
    handleClose() {
      this.dialogVisible = false
    },

    async handleExpandChange(row, rows) {
      // console.log('展开或关闭', row, rows)
      this.rentid = row.id
      const isExpand = rows.find((item) => { return item.id === row.id })
      // console.log(isExpand)

      if (isExpand) {
        const res = await getRentContractList(row.id)
        // console.log(res)
        this.$set(row, 'rentList', res.data) // 使用 $set 确保响应性
      }
    },
    // 格式化合同状态
    formatStatus(row) {
      const map = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'

      }
      return map[row.status]
    },
    // 格式化tag类型
    formatInfoType(status) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      // return 格式化之后的中文显示
      return MAP[status]
    },
    // 退租
    async outRent(id) {
      const res = await outRentAPI(id)
      console.log(res)
    },
    // 续租
    async continueRent(id) {
      this.dialogVisible = true
      // this.rentForm.enterpriseId = id
      // console.log(id)
      this.rentForm.enterpriseId = this.rentid
      this.rentForm.type = 1
      // const res = await getRentContractList(this.rentid)
      // this.rentForm.enterpriseId = res.data.enterpriseId

      // 获取楼宇
      const res1 = await getBuildingList()
      // console.log(res)
      this.bulidingList = res1.data.rows
    },
    handleLook(id) {
      this.$router.push({
        path: '/enterpriseDetail',
        query: {
          id: id
        }
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.app-wrapper {
  padding: 20px;
}
.search-container{
  display: flex;
  align-items: center;
  margin-right: 10px;
  padding-bottom: 20px;
}
.search-label{
  margin-right: 10px;
}
.search-main{
  width: 300px;
  margin-right: 10px;
}
.pagination-container{
  text-align: right;
}
::v-deep .el-form{
  padding: 20px;
}
::v-deep .el-upload{
  display: inline;
  height: 50px;
}
::v-deep .upload-demo{
  text-align: left
}
::v-deep .el-button--small{
  padding: 9px 20px;
}
::v-deep .el-icon-upload2{
  margin-right: 8px;
}
::v-deep .el-dialog__footer{
  background-color: #F4F6F8 !important;
}
::v-deep .el-input
{
  width: 350px;
}

</style>
